/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */

<!-- 新增服务镜像弹窗 -->

<template>
    <sf-form ref="form"
             class="add-image__form"
             :label-width="120">
        <sf-form-item v-if="showDefaultAddress && !isEdit">
            <sf-fieldlabel>
                <lang>服务镜像地址</lang>
            </sf-fieldlabel>
            <sf-textfield
                ref="fieldName"
                v-model="submitData.address"
                :default-width="defaultWidth"
                :allow-blank="false"
                :utf8-length="false"
                :validator="_addressValidator"
                :blur-trim="true"
                :placeholder="_('请输入镜像地址')" />
        </sf-form-item>
        <sf-form-item v-if="!showDefaultAddress">
            <sf-fieldlabel>
                <lang>服务镜像地址</lang>
            </sf-fieldlabel>
            <span>registry.ai.geniusai.com/{{ userID }}/</span>
            <sf-textfield
                ref="fieldName"
                v-model="submitData.imageName"
                :default-width="100"
                :allow-blank="false"
                :utf8-length="false"
                :validator="_nameValidator"
                :blur-trim="true"
                :placeholder="_('请输入镜像地址')" />
            <span>:</span>
            <sf-textfield
                ref="fieldName"
                v-model="submitData.imageVersion"
                :default-width="100"
                :allow-blank="false"
                :utf8-length="false"
                :validator="_versionValidator"
                :blur-trim="true"
                :placeholder="_('请输入版本')" />
        </sf-form-item>
        <sf-form-item class="image-tag">
            <sf-fieldlabel>
                <lang>镜像标签</lang>
            </sf-fieldlabel>
            <sf-checkbox-group v-model="tagIDs">
                <sf-checkbox
                    v-for="(tag, index) in tagList"
                    :key="index"
                    :default-disabled="tag.disabled"
                    :check-value="tag.value">
                    {{ tag.name }}<span class="gray">（{{ tag.description }}）</span>
                </sf-checkbox>
            </sf-checkbox-group>
        </sf-form-item>
        <sf-form-item v-if="showAlgorithmType">
            <sf-fieldlabel>
                <lang>算法模板名称</lang>
            </sf-fieldlabel>
            <sf-textfield
                ref="algorithmName"
                v-model="submitData.algorithmName"
                :default-width="defaultWidth"
                :max-length="30"
                :allow-blank="false"
                :utf8-length="false"
                vtype="name"
                :blur-trim="true"
                :placeholder="_('请输入算法模板名称')" />
        </sf-form-item>
        <sf-form-item v-if="showAlgorithmType">
            <sf-fieldlabel>
                <lang>算法场景</lang>
            </sf-fieldlabel>
            <sf-select v-model="submitData.algorithmTypeID"
                       :default-width="defaultWidth"
                       :allow-search="true"
                       :allow-blank="false"
                       :options="algorithmTypeList"
                       display-field="name"
                       value-field="id"
                       :show-add-btn="true"
                       @on-add="_addAlgorithmType" />
        </sf-form-item>
        <div v-if="showAlgorithmType && !isEdit">
            <add-algorithm-params ref="algorithmParams" />
        </div>
        <sf-form-item v-if="showAlgorithmType">
            <sf-fieldlabel>
                <lang>程序入口</lang>
            </sf-fieldlabel>
            <sf-textfield
                ref="fieldName"
                v-model="submitData.entryPoint"
                :default-width="defaultWidth"
                :utf8-length="false"
                :blur-trim="true"
                :placeholder="_('请输入程序入口')" />
        </sf-form-item>
        <sf-form-item>
            <sf-fieldlabel>
                <lang>描述</lang>
            </sf-fieldlabel>
            <sf-textarea
                v-model="submitData.description"
                :placeholder="_('最多300字（选填）')"
                :default-width="defaultWidth"
                :max-length="300"
                :utf8-length="false" />
        </sf-form-item>
    </sf-form>
</template>
<style lang="less">
    .add-image__form{
        padding: 10px 32px;
    }
    .image-tag{
        display: flex;
        .sfv-checkbox-group .sfv-checkbox{
            margin: 8px 8px 0 4px;
            display: block;
        }
    }
</style>

<script>
const DEFAULT_WIDTH = 453;
const DEFAULT_VALUE = {
    address:'',
    description:'',
    algorithmTypeID:'',
    algorithmName:'',
    imageName:'',
    imageVersion:'',
    tagIDs:[],
    isAutoMl:0,
    paramsDescription:'',
    paramFormat:1,
    entryPoint:''
};
import trainingUrlAdapter from 'src/home/mod_common/training_url_adapter';
import store from 'src/vuex/store';
let userID = store.state.userId;
const CARD_URLS = {
    get: trainingUrlAdapter(`user/${userID}/algorithmType`),
    post:trainingUrlAdapter(`user/${userID}/algorithmType`)
};

import addAlgorithmTypeForm from 'src/home/mod_cluster/algorithm_manager/label_form/add_algorithm_type.vue';

import addAlgorithmParams from 'src/home/mod_cluster/common/common_form/add_algorithm_params.vue';

export default {
    components:{
        addAlgorithmParams
    },
    computed: {
        defaultWidth () {
            return DEFAULT_WIDTH;
        },
        showAlgorithmType () {
            return this.tagIDs.indexOf('public_train') > -1 && !this.hidePublicTrain;
        }

    },
    data () {
        return {
            hidePublicTrain:false,
            isEdit:false,
            submitData: { ...DEFAULT_VALUE },
            tagIDs:[],
            tagList:[{
                value:_('public_notebook'),
                name:_('Code Studio镜像'),
                description:_('可供其他Code Studio使用'),
                diabled:false
            }, {
                value:_('public_service'),
                name:_('服务部署镜像'),
                diabled:false,
                description:_('可用于服务部署')
            }],
            algorithmTypeList:[],
            showDefaultAddress:true,
            userID
        };
    },

    methods: {
        _addressValidator (value) {
            let datasetNameReg = /[\u4E00-\u9FA5]/g;
            if (datasetNameReg.test(value)) {
                return _('镜像地址不能输入中文');
            }
            return true;
        },

        _nameValidator (value) {
            let datasetNameReg = /^[a-z0-9][a-z0-9-]*[a-z0-9]$/;
            if (!datasetNameReg.test(value)) {
                return _('必须以小写字母数字开头，横线不能为首尾,且不支持单个字符，仅支持横线、小写字母、数字');
            }
            return true;
        },
        _versionValidator (value) {
            let datasetNameReg = /^[\w][\w.-]{0,127}$/;
            if (!datasetNameReg.test(value)) {
                return _('必须以字母数字开头，而且仅支持横线、字母、数字、点和下划线');
            }
            return true;
        },
        getJsonValue () {
            this.submitData.tagIDs = this.tagIDs;
            if (this.tagIDs.indexOf('public_train') < 0) {
                this.submitData.algorithmTypeID = '';
                this.submitData.algorithmName = '';
                this.submitData.paramsDescription = '';
            } else {
                this.submitData.paramsDescription = this.$refs.algorithmParams && this.$refs.algorithmParams.getJsonValue() || '';
            }
            if (!this.submitData.entryPoint) {
                this.submitData.entryPoint = '';
            }
            return this.submitData;
        },
        setJsonValue (data) {
            let {tags} = data;
            this.tagIDs = tags.map(item=>item.id);
            this.hidePublicTrain = this.tagIDs.indexOf('public_train') > -1;
            this.tagList[1].disabled = this.hidePublicTrain;

            Object.assign(this.submitData, data);
        },

         // 获取算法场景
        async refreshCardInfo () {
            let jsonData = await this.$ajax.get(CARD_URLS.get, {keyword:''});
            let {success, msg, data} = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                return;
            }
            this.algorithmTypeList = data;
        },

        // 新增算法场景弹窗
        _createAlgorithmTypeFormWin () {
            if (!this.algorithmTypeFormWin) {
                this.algorithmTypeFormWin = this.$modal(addAlgorithmTypeForm, {
                    autoDestory: true
                });
            }
            return this.algorithmTypeFormWin;
        },

        // 新增算法场景
        _addAlgorithmType () {
            let formWin = this._createAlgorithmTypeFormWin();
            formWin.open({
                reset: true,
                title: _('新增算法场景'),
                submit: () => {
                    let ajaxParams = formWin.formRoot.getJsonValue();
                    this.ajaxSubmitCardInfo(ajaxParams, formWin);
                }
            });
        },

         // 新增/编辑算法的卡片信息
        async ajaxSubmitCardInfo (params, formWin) {
            formWin.$mask();
            let jsonData = await this.$ajax.post(CARD_URLS.post, params);
            formWin.$unmask();
            let {success, msg} = jsonData;
            if (!success) {
                return this.$showErr(msg || _('新增算法场景失败'));
            }
            this.$ok(_('新增算法场景成功'));
            formWin.hide();
            this.refreshCardInfo();

        }
    }
};
</script>
